from decimal import Decimal

from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime
from typing import Optional, List, Generic

from app.schemas.simulation_result_total import SimulationResultTotalSchema, SimulationResultTotalOutDetail
from app.utils.Result import T


class SimulationCreate(BaseModel):
    env_param_id: int
    name: Optional[str] = None


class SimulationUpdate(BaseModel):
    name: Optional[str] = None


class SimulationInDB(BaseModel):
    simulation_id: int
    env_param_id: int
    name: Optional[str] = None
    created_at: datetime

    class Config:
        orm_mode = True

class SimulationWithResults(BaseModel):
    simulation_id: int
    env_param_id: int
    name: Optional[str]
    created_at: datetime
    results: List[SimulationResultTotalSchema] = []  # 嵌套返回

    class Config:
        from_attributes = True

class SimulationQuery(BaseModel):
    keyword: Optional[str] = Field(None, description="关键词，支持名称模糊搜索")
    page: int = Field(1, ge=1, description="页码，从1开始")
    page_size: int = Field(10, ge=1, le=100, description="每页大小，最大100")

class PageResult(BaseModel, Generic[T]):
    items: List[T]
    total: int
    page: int
    page_size: int

# SimulationResult 的 Pydantic 模型
class SimulationResultSchemaDetail(BaseModel):
    simulation_result_id: int
    time_point: datetime
    battery_energy: Decimal
    solar_power: Decimal
    grid_power: Decimal
    total_power: Decimal
    wind_power: Decimal
    solar_cost: Decimal
    wind_cost: Decimal
    grid_cost: Decimal
    solar_emission: Decimal
    wind_emission: Decimal
    grid_emission: Decimal

    class Config:
        orm_mode = True  # 支持 ORM 模型转换

class SimulationResultTotalMapSchema(BaseModel):
    id: int
    simulation_result: SimulationResultSchemaDetail  # 嵌套 SimulationResult

    class Config:
        orm_mode = True

# SimulationResultTotalMap 你可能不需要暴露，这里假设你想直接嵌套 SimulationResult
# SimulationResultTotal 的 Pydantic 模型
class SimulationResultTotalSchemaDetail(BaseModel):
    simulation_result_total_id: int
    battery_energy: Decimal
    solar_power: Decimal
    grid_power: Decimal
    wind_power: Decimal
    total_power: Decimal
    solar_cost: Decimal
    wind_cost: Decimal
    grid_cost: Decimal
    solar_emission: Decimal
    wind_emission: Decimal
    grid_emission: Decimal
    period_unit: str
    period: int
    name: str
    strategy: str
    # 关联的 simulation_result 列表
    result_maps: Optional[List[SimulationResultTotalMapSchema]] = []

    class Config:
        orm_mode = True

# Simulation 的 Pydantic 模型，顶层结构
class SimulationWithResultsDetail(BaseModel):
    simulation_id: int
    env_param_id: int
    name: Optional[str]
    created_at: datetime
    results: List[SimulationResultTotalSchemaDetail] = []

    class Config:
        orm_mode = True